package calculator.web;

import org.apache.wicket.ajax.AjaxEventBehavior;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.form.AjaxFormChoiceComponentUpdatingBehavior;
import org.apache.wicket.ajax.form.OnChangeAjaxBehavior;
import org.apache.wicket.markup.html.WebPage;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.*;
import org.apache.wicket.markup.html.list.ListItem;
import org.apache.wicket.markup.html.list.ListView;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.model.Model;
import org.apache.wicket.model.PropertyModel;

import java.util.ArrayList;
import java.util.List;


public class HomePage extends WebPage {

    Integer hours = 0;
    Integer minutes = 0;
    Integer frequency = 7;
    Integer dayLength = 14;

    private Label wastedTimePerWeekLabel = new Label("wastedTimePerWeek");
    private Label wastedTimePerMonthLabel = new Label("wastedTimePerMonth");
    private Label wastedTimePerYearLabel = new Label("wastedTimePerYear");
    private Label wastedTimePerTenYearsLabel = new Label("wastedTimePerTenYears");

    private TextField<Integer> hoursField = new TextField<Integer>("hours");
    private TextField<Integer> minutesField = new TextField<Integer>("minutes");

    private RadioGroup dayLengthRadioGroup = new RadioGroup("dayLengthRadioGroup", new PropertyModel(this, "dayLength"));
    private RadioGroup frequencyRadioGroup = new RadioGroup("frequencyRadioGroup", new PropertyModel(this, "frequency"));
    private RadioGroup   hoursRadioGroup = new RadioGroup("hoursRadioGroup", new PropertyModel(this, "hours"));
    private RadioGroup   minutesRadioGroup = new RadioGroup("minutesRadioGroup", new PropertyModel(this, "minutes"));
    private FeedbackPanel feedBackPanel = new FeedbackPanel("feedBack");


    public HomePage() {
        Form form = new Form("form");
        add(form);
        form.setDefaultModel(new CompoundPropertyModel(this));
        form. add(feedBackPanel);
        feedBackPanel.setOutputMarkupId(true);
        wastedTimePerWeekLabel.setOutputMarkupId(true);
        wastedTimePerMonthLabel.setOutputMarkupId(true);
        wastedTimePerYearLabel.setOutputMarkupId(true);
        wastedTimePerTenYearsLabel.setOutputMarkupId(true);

        hoursField.setOutputMarkupId(true);
        minutesField.setOutputMarkupId(true);

        hoursField.add(new OnChangeAjaxBehavior() {
            @Override
            protected void onUpdate(AjaxRequestTarget target) {
                updateTime(target);
                target.addComponent(hoursRadioGroup);
            }
            @Override
            protected void onError(AjaxRequestTarget target, RuntimeException e) {
                super.onError(target, e);

                 target.addComponent(hoursField);
                 target.addComponent(feedBackPanel);

            }
        });
         hoursField.add(new AjaxEventBehavior("onBlur") {
                 @Override
                 protected void onEvent(AjaxRequestTarget target) {
                     if (!hoursField.getValue().equals(hours.toString())){
                         hoursField.clearInput();
                         target.addComponent(hoursField);
                         updateTime(target);


                     }
                 }
             });
        minutesField.add(new OnChangeAjaxBehavior() {
            @Override
            protected void onUpdate(AjaxRequestTarget target) {
                updateTime(target);
                target.addComponent(minutesRadioGroup);
            }
             @Override
            protected void onError(AjaxRequestTarget target, RuntimeException e) {
                super.onError(target, e);

                 target.addComponent(feedBackPanel);

            }
        });
             minutesField.add(new AjaxEventBehavior("onBlur") {
                 @Override
                 protected void onEvent(AjaxRequestTarget target) {
                     if (!minutesField.getValue().equals(minutes.toString())){
                         minutesField.clearInput();
                         target.addComponent(minutesField);
                         updateTime(target);

                         
                     }
                 }
             });

        initFrequency(form);
        initHours(form);
        initMinutes(form);
        initDayLength(form);

        form.add(wastedTimePerMonthLabel);
        form.add(wastedTimePerWeekLabel);
        form.add(wastedTimePerYearLabel);
        form.add(wastedTimePerTenYearsLabel);
        form.add(minutesField);
        form.add(hoursField);

//        wastedHoursPerWeekLabel.add(new AjaxFormComponentUpdatingBehavior("onChange") {
//
//            @Override
//            protected void onUpdate(AjaxRequestTarget target) {
//
//                System.err.println("AjaxFormComponentUpdatingBehavior");
//                wastedHoursPerWeek = getHours() * 7;
//                target.addComponent(wastedHoursPerWeekLabel);
//            }
//        });


    }

    private void initDayLength(Form form) {
        List<Integer> kuk;
        ListView<Integer> list;


        kuk = new ArrayList<Integer>();
        int aa[] = {6, 8, 10, 12, 14, 16, 18, 24};
        for (int i : aa) {
          kuk.add(i);
        }
        list = new ListView<Integer>("list", kuk) {
           protected void populateItem(ListItem<Integer> item) {
               Radio radio = new Radio("radio", new Model(item.getModelObject()));
               item.add(radio);
               radio.add(new Label("value", new Model(item.getModelObject())));
           }
       };
        dayLengthRadioGroup.add(list);
        dayLengthRadioGroup.add(new AjaxFormChoiceComponentUpdatingBehavior() {
            @Override
            protected void onUpdate(AjaxRequestTarget target) {
                updateTime(target);
            }
        });
        form.add(dayLengthRadioGroup);
//        myInt.add(new AjaxFormChoiceComponentUpdatingBehavior() {
//            @Override
//            protected void onUpdate(AjaxRequestTarget target) {
//                System.err.println(target.getLastFocusedElementId());
//            }
//        });
    }

    private void initMinutes(Form form) {
        List<Integer> kuk;
        ListView<Integer> list;


        int kk[] = {0, 15, 30, 45, 60, 75, 90};
        kuk = new ArrayList<Integer>();
        for (int i : kk) {
            kuk.add(i);
        }

        list = new ListView<Integer>("list", kuk) {
            protected void populateItem(ListItem<Integer> item) {
                Radio radio = new Radio("radio", new Model(item.getModelObject()));
                item.add(radio);
                radio.add(new Label("value", new Model(item.getModelObject())));
            }
        };
        minutesRadioGroup.add(list);
        minutesRadioGroup.add(new AjaxFormChoiceComponentUpdatingBehavior() {
            @Override
            protected void onUpdate(AjaxRequestTarget target) {
                target.addComponent(minutesField);
                updateTime(target);
            }


        });
        list.setOutputMarkupId(true);
        minutesRadioGroup.add(list);
        form.add(minutesRadioGroup);
    }

    private void initHours(Form form) {
        ListView<Integer> list;
        List<Integer> kuk = new ArrayList<Integer>();
        for (int i = 0; i < 13; i++) {
            kuk.add(i);
        }
        form.add(hoursRadioGroup);
        list = new ListView<Integer>("list", kuk) {
           protected void populateItem(ListItem<Integer> item) {
               Radio radio = new Radio("radio", new Model(item.getModelObject()));
               item.add(radio);
               radio.add(new Label("value", new Model(item.getModelObject())));
           }
       };
        hoursRadioGroup.add(list);
        hoursRadioGroup.add(new AjaxFormChoiceComponentUpdatingBehavior() {
            @Override
            protected void onUpdate(AjaxRequestTarget target) {
                target.addComponent(hoursField);
              
                updateTime(target);
            }
        });
    }

    private void initFrequency(Form form) {
        List<Integer> foo = new ArrayList<Integer>();
        for (int i = 1; i < 8; i++) {
          foo.add(i);
        }
        ListView<Integer> list = new ListView<Integer>("list", foo) {
            protected void populateItem(ListItem<Integer> item) {
                Radio radio = new Radio("radio", new Model(item.getModelObject()));
                item.add(radio);
                item  .setOutputMarkupId(true);   radio  .setOutputMarkupId(true);
                radio.add(new Label("value", new Model(item.getModelObject())));
            }
        };
        list.setOutputMarkupId(true);

        frequencyRadioGroup.add(list);
        frequencyRadioGroup.add(new AjaxFormChoiceComponentUpdatingBehavior() {
            @Override
            protected void onUpdate(AjaxRequestTarget target) {
                updateTime(target);
            }
        });
        form.add(frequencyRadioGroup);
        frequencyRadioGroup.setOutputMarkupId(true);

    }

    private void updateTime(AjaxRequestTarget target) {

        target.addComponent(wastedTimePerWeekLabel);
        target.addComponent(wastedTimePerMonthLabel);
        target.addComponent(wastedTimePerYearLabel);
        target.addComponent(wastedTimePerTenYearsLabel);

        target.addComponent(dayLengthRadioGroup);
        target.addComponent(frequencyRadioGroup);
        target.addComponent(feedBackPanel);

    }

    public Integer getHours() {
        if (hours == null)
            hours = Integer.valueOf(0);
        return hours;
    }

    public void setHours(Integer hours) {
        if (hours == null)
            hours = Integer.valueOf(0);

        this.hours = hours;
    }

    public String getWastedTimePerWeek() {

        return convertTime(calculate());
    }

    private Long calculate() {

        return ((long) getHours() * 60 + getMinutes()) * frequency;
    }

    public String getWastedTimePerMonth() {
        double time = (double) 30 / 7;
        return convertTime((long) ((double) calculate() * time));
    }

    public String getWastedTimePerYear() {
        double time = (double) 355 / 7;
        return convertTime((long) ((double) calculate() * time));
    }

    public String getWastedTimePerTenYears() {
        double time = (double) 3550 / 7;
        return convertTime((long) ((double) calculate() * time));
    }

    public Integer getMinutes() {
        return minutes;
    }

    public void setMinutes(Integer minutes) {
        this.minutes = minutes;
    }

    private String convertTime(Long minutes) {
        int hours = 0;
        int days = 0;
        int weeks =0;
        int months = 0;
        int years =0;

        int minutesPerDay = dayLength * 60;

        days = (int) (minutes / minutesPerDay);
        minutes = minutes % minutesPerDay;
        hours = (int) (minutes / 60);
        minutes = minutes % 60;
        if (days >= 355) {
            years = days / 355;
            days = days % 355;
        }
        if (days >= 30) {
            months = days / 30;
            days = days % 30;
        }
        if (days >= 7) {
            weeks = days / 7;
            days = days % 7;
        }

        String result = "";
        if (years > 0) {
            result = result + years;
            if (years == 1) {
                result = result + " year, ";
            } else {
                result = result + " years, ";
            }
        }
        if (months > 0) {
            result = result + months;
            if (months == 1) {
                result = result + " month, ";
            } else {
                result = result + " months, ";
            }
        }
        if (weeks > 0) {
            result = result + weeks;
            if (weeks == 1) {
                result = result + " week, ";
            } else {
                result = result + " weeks, ";
            }
        }
        if (days > 0) {
            result = result + days;
            if (days == 1) {
                result = result + " day, ";
            } else {
                result = result + " days, ";
            }
        }

        result = result + hours;
        if (hours == 1) {
            result = result + " hour and ";
        } else {
            result = result + " hours and ";
        }


        result = result + minutes;
        if (minutes == 1) {
            result = result + " minute";
        } else {
            result = result + " minutes";
        }

        return result;
    }

}
